#include <algorithm>
#include "ECS/Assembly.h"
#include "ECS/Component.h"

namespace ECS
{

	mtBEGIN(Assembly)
		mtCONSTRUCTOR();
	mtEND


	void Assembly::sendMessage( TypeID messageID )
	{
		for (auto it = _components.begin(); it != _components.end(); ++it)
		{
			Component* component = *it;
			mtCALL_EX((component->getMetaTable()), component, messageID);
		}
	}

	Component* Assembly::getComponent( TypeID type ) const
	{
		for (auto it = _components.begin(); it != _components.end(); ++it)
		{
			Component* c = *it;
			if (c->getMetaTable()->isSubclass(type))
				return c;
		}

		return nullptr;
	}

	void Assembly::destroy( Component* component )
	{
		_components.erase(std::find(_components.begin(), _components.end(), component));
		delete component;
	}

	void Assembly::addComponent( Component* component )
	{
		component->_assembly = this;
		_components.push_back(component);
	}

	void Assembly::onDestroyed()
	{

	}

	void Assembly::destroy()
	{
		_isDestroyed = true;
	}

	bool Assembly::isDestroyed() const
	{
		return _isDestroyed;
	}

	void Assembly::destroyImmediately()
	{
		for (auto it = _components.begin(); it != _components.end(); ++it)
			delete *it;

		_components.clear();
		onDestroyed();
		delete this;
	}

	Assembly::Assembly() : _isDestroyed(false)
	{

	}

	Assembly::~Assembly()
	{

	}

	bool Assembly::hasComponent( TypeID type ) const 
	{
		return getComponent(type) != nullptr;
	}

}